//
//  XZMakeARollVC.m
//  Teecloud
//
//  Created by PC on 2018/11/5.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "XZMakeARollVC.h"
#import "XZLeaveApplyDetailVC.h"
//Cell/View
#import "XZRollView.h"
#import "XZRoomNameCell.h"
//Model
#import "XZRoomNaming.h"
#import "XZMemberList.h"
#import "XZListData.h"
@interface XZMakeARollVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
//签到二维码 Id（30.88接口）或者考勤时段序号（30.87接口）
@property (nonatomic, copy) NSString *qrcodeId;
@property (nonatomic, strong) XZRollView *rollView;
@property (nonatomic, strong) UIButton *rightBtn;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) UICollectionView *collectionView;
//导航栏空格
@property (nonatomic, strong) UIBarButtonItem *spaceItem;

@end
#define Identifier @"XZRoomNameCell"
@implementation XZMakeARollVC
//视图消失将其隐藏
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.rollView hide];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"随堂点名";
    self.view.backgroundColor = kWhiteColor;
    if ([self.model.TimeType isEqualToNumber:@(1)]) {
        //30.87接口
        [self GetRoomNamingList1];
        self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(GetRoomNamingList1)];
    }else if ([self.model.TimeType isEqualToNumber:@(2)]){
        //30.88接口
       [self GetRoomNamingList2];
        self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(GetRoomNamingList2)];
    }
}

/**
 GroupConfig.TimeType = 1
 获取随堂点名列表[上班制]
 */
- (void)GetRoomNamingList1{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:self.qrcodeId forKey:@"timeNo"];

    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetRoomNamingList1&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakself.collectionView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                [weakself.dataSource removeAllObjects];
                XZRoomNaming *model = [XZRoomNaming mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                [weakself.dataSource addObjectsFromArray:model.MemberList];
                self.rollView.listData = model.ListData;
                //构建下拉列表
                if (kIsEmptyString(weakself.qrcodeId)) {
                    for (XZListData *listModel in model.ListData) {
                        if (listModel.IsSelected) {
                            //考勤时段序号
                            weakself.qrcodeId = listModel.Id;
                            [weakself.rightBtn setTitle:[NSString stringWithFormat:@"%@",listModel.Name] forState:UIControlStateNormal];
                            UIBarButtonItem *signItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightBtn];
                            self.navigationItem.rightBarButtonItems = @[self.spaceItem,signItem];
                        }
                    }
                }
                if (weakself.dataSource.count == 0) {
                    [weakself.collectionView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [weakself.collectionView.mj_header endRefreshing];
                [weakself.collectionView reloadData];
            }else{
                [weakself.collectionView.mj_header endRefreshing];
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [weakself.collectionView.mj_header endRefreshing];
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
/**
 GroupConfig.TimeType = 2
 获取随堂点名列表[机动式]
 */
- (void)GetRoomNamingList2{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:self.qrcodeId forKey:@"qrcodeId"];
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetRoomNamingList2&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakself.collectionView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                [weakself.dataSource removeAllObjects];
                XZRoomNaming *model = [XZRoomNaming mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                [weakself.dataSource addObjectsFromArray:model.MemberList];
                self.rollView.listData = model.ListData;
                //构建下拉列表
                if (kIsEmptyString(weakself.qrcodeId)) {
                    for (XZListData *listModel in model.ListData) {
                        if (listModel.IsSelected) {
                            //签到二维码 Id
                            weakself.qrcodeId = listModel.Id;
                            [weakself.rightBtn setTitle:[NSString stringWithFormat:@"%@",listModel.Name] forState:UIControlStateNormal];
                            UIBarButtonItem *signItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightBtn];
                            self.navigationItem.rightBarButtonItems = @[self.spaceItem,signItem];
                        }
                    }
                }
                [weakself.collectionView.mj_header endRefreshing];
                if (weakself.dataSource.count == 0) {
                    [weakself.collectionView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [weakself.collectionView reloadData];
            }else{
                [weakself.collectionView.mj_header endRefreshing];
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [weakself.collectionView.mj_header endRefreshing];
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
#pragma mark -  CollectionViewDatasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    kWeakObject(self)
    XZRoomNameCell *roomNameCell = [collectionView dequeueReusableCellWithReuseIdentifier:Identifier forIndexPath:indexPath];
    XZMemberList *model = self.dataSource[indexPath.row];
    roomNameCell.model = model;
    //请假
    roomNameCell.memberBlockOne = ^(XZMemberList * _Nonnull model) {
        XZLeaveApplyDetailVC *leaveApplyDetailVC = [[XZLeaveApplyDetailVC alloc]init];
        leaveApplyDetailVC.id = model.ApplyId;
        [weakself.navigationController pushViewController:leaveApplyDetailVC animated:true];
    };
    //已到 未到 请假
    roomNameCell.memberBlockTwo = ^(NSString * _Nonnull code) {
        [weakself PostRoomNamingInfo:code memberUserId:model.UserId];
    };
    return roomNameCell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((DEVICE_WIDTH - 60)/3, 150);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(15, 15, 0, 15);
}

/**
 提交随堂点名数据

 @param statusCode 操作状态（已到=1，未到=2，请假=3）
 @param memberUserId 成员用户 Id
 */
- (void)PostRoomNamingInfo:(NSString *)statusCode memberUserId:(NSString *)memberUserId{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:memberUserId forKey:@"memberUserId"];
    [dict setValue:statusCode forKey:@"statusCode"];
    [dict setValue:self.qrcodeId forKey:@"selectedItemId"];
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=PostRoomNamingInfo&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                if ([weakself.model.TimeType isEqualToNumber:@(1)]) {
                    //30.87接口
                    [weakself GetRoomNamingList1];
                }else if ([weakself.model.TimeType isEqualToNumber:@(2)]){
                    //30.88接口
                    [weakself GetRoomNamingList2];
                }
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}

/**
 点击按钮切换下拉列表
 隐藏则显示，反之
 @param sender 按钮
 */
- (void)selectListData:(UIButton *)sender{
    UIWindow *rootWindow = [UIApplication sharedApplication].keyWindow;
    for (UIView *view in rootWindow.subviews) {
        if (view == self.rollView) {
              [self.rollView hide];
        }else{
           [self.rollView show];
        }
    }
}
- (void)rollViewSelectRow:(XZListData *)model{
    [self.rightBtn setTitle:model.Name forState:UIControlStateNormal];
    self.qrcodeId = model.Id;
    [self.collectionView.mj_header beginRefreshing];
}
#pragma mark - Setter
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc]init];
    }
    return _dataSource;
}
- (UIBarButtonItem *)spaceItem{
    if (!_spaceItem) {
        _spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        _spaceItem.width = -15;
    }
    return _spaceItem;
}
-(UIButton *)rightBtn{
    if (!_rightBtn) {
        _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightBtn.frame = CGRectMake(0, 0, 100, 30);
        [_rightBtn setImage:[UIImage imageNamed:@"down-white-64"] forState:UIControlStateNormal];
        [_rightBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
        _rightBtn.titleLabel.font = [UIFont systemFontOfSize: 15.0];
        _rightBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
        [_rightBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -30, 0, 0)];
        [_rightBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 80, 0, 0)];
        [_rightBtn addTarget:self action:@selector(selectListData:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightBtn;
}
- (XZRollView *)rollView{
    if (!_rollView) {
        kWeakObject(self)
        _rollView =[XZRollView viewFromXib];
        _rollView.frame = CGRectMake(0, kNavBarAndStatusBarHeight, DEVICE_WIDTH, DEVICE_HEIGHT);
        _rollView.backgroundColor = kClearColor;
        _rollView.RollViewBlock = ^(XZListData * _Nonnull model) {
            [weakself rollViewSelectRow:model];
        };
    }
    return _rollView;
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        layout.minimumLineSpacing = 15;
        layout.minimumInteritemSpacing = 0;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT-kBottomSafeHeight) collectionViewLayout:layout];
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.backgroundColor = kWhiteColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = false;
        _collectionView.showsHorizontalScrollIndicator = false;
        //注册cell
        [_collectionView registerNib:[UINib nibWithNibName:@"XZRoomNameCell" bundle:nil] forCellWithReuseIdentifier:Identifier];
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}
@end
